package com.cloudweb.oa.utils;

import org.apache.tools.ant.taskdefs.Javadoc;

import java.io.IOException;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class GetClassUtil {

    public static void main(String[] args) {
        // String PakageString = "org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth";
        // String PakageString = "org.openxmlformats.schemas.wordprocessingml.x2006.main.impl.CTRowImpl";
        // String PakageString = "org.apache.xmlbeans.impl.values.XmlObjectBase";
        // String PakageString = "org.apache.poi.ss.usermodel.Font";
        // String PakageString = "org.apache.poi.xssf.usermodel.XSSFCellStyle";
        String PakageString = "javax.xml.transform.TransformerFactory";
        PakageString = "org.openxmlformats.schemas.wordprocessingml.x2006.main.FontsDocument";

        GetFilePathByPackage(PakageString);
        System.out.println("\r\n");
        // 获取Class路径
        String alljar = System.getProperty("java.class.path");
        String[] alljarpath = alljar.split(";");
        // 根据路径遍历，该路径下的Jar包是否有该包,有就打印
        for (String jarpath : alljarpath) {
            if (jarpath.contains("jar")) {
                String[] jar = new String[2];
                jar[0] = jarpath;
                jar[1] = PakageString;
                getClassNameByJarAndPackage(jar);
            }
        }
    }

    /**
     * 根据类名打印JVM加载的类对应的Jar包路径，如GetFilePathByPackage("java.util")。
     *
     * @param PakageString 类名
     */
    public static void GetFilePathByPackage(String PakageString) {
        System.out.println("查找的类：" + PakageString);

        try {
            Class<?> c = Class.forName(PakageString);
            ProtectionDomain pd = c.getProtectionDomain();
            CodeSource cs = pd.getCodeSource();
            System.out.println("加载的类对应的路径：" + cs.getLocation().toString());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

    /**
     * 根据jar包路径和包名来查询jar包中是否含有有关类
     *
     * @param jar jar[0] jar路径 jar[1] 包名
     */
    @SuppressWarnings("resource")
    public static void getClassNameByJarAndPackage(String[] jar) {
        String jarFilePath = jar[0];
        String packagePath = jar[1].replace(".", "/");
        try {
            JarFile jarFile = new JarFile(jarFilePath);
            Enumeration<JarEntry> entrys = jarFile.entries();
            while (entrys.hasMoreElements()) {
                JarEntry jarEntry = entrys.nextElement();
                String entryName = jarEntry.getName();
                if (entryName.equals(packagePath + ".class")) {
                    System.out.println("类路径：" + entryName + "\r\n" + "jar包的路径：" + jarFilePath);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}